/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.orders.web;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.account.entity.Account;
import com.jeeplus.modules.dynamicrecord.entity.DynamicRecord;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.recharge.entity.Recharge;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.orders.entity.Orders;
import com.jeeplus.modules.orders.service.OrdersService;

/**
 * 交易订单Controller
 * @author freedom
 * @version 2020-09-26
 */
@Controller
@RequestMapping(value = "${adminPath}/orders/orders")
public class OrdersController extends BaseController {

	@Autowired
	private OrdersService ordersService;
	
	@ModelAttribute
	public Orders get(@RequestParam(required=false) String id) {
		Orders entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = ordersService.get(id);
		}
		if (entity == null){
			entity = new Orders();
		}
		return entity;
	}
	
	/**
	 * 交易订单列表页面  出售中
	 */
	@RequiresPermissions("orders:orders:list")
	@RequestMapping(value = {"list", ""})
	public String list(Orders orders, Model model) {
		model.addAttribute("orders", orders);
		return "modules/orders/ordersList";
	}
	
		/**
	 * 交易订单列表数据  出售中
	 */
	@ResponseBody
	@RequiresPermissions("orders:orders:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Orders orders, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Orders> page = ordersService.findPage(new Page<Orders>(request, response), orders);
		return getBootstrapData(page);
	}

	/**
	 * 交易订单列表页面  待付款  待确认
	 */
	@RequiresPermissions("orders:orders:list")
	@RequestMapping(value = "/trading")
	public String trading(Orders orders, Model model) {
		model.addAttribute("orders", orders);
		return "modules/orders/ordersTradingList";
	}

	/**
	 * 交易订单列表数据  待付款  待确认
	 */
	@ResponseBody
	@RequiresPermissions("orders:orders:list")
	@RequestMapping(value = "/tradingData")
	public Map<String, Object> tradingData(Orders orders, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Orders> page = ordersService.findTradingPage(new Page<Orders>(request, response), orders);
		return getBootstrapData(page);
	}

	/**
	 * 交易订单列表页面  交易成功
	 */
	@RequiresPermissions("orders:orders:list")
	@RequestMapping(value = "successList")
	public String successList(Orders orders, Model model) {
		model.addAttribute("orders", orders);
		return "modules/orders/ordersSuccessList";
	}

	/**
	 * 交易订单列表数据  交易成功
	 */
	@ResponseBody
	@RequiresPermissions("orders:orders:list")
	@RequestMapping(value = "successData")
	public Map<String, Object> successData(Orders orders, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Orders> page = ordersService.findSuccessPage(new Page<Orders>(request, response), orders);
		return getBootstrapData(page);
	}


	/**
	 * 交易订单列表数据(goods条件查询用)
	 */
	@ResponseBody
	@RequiresPermissions("orders:orders:list")
	@RequestMapping(value = "dataForGoods")
	public Map<String, Object> dataForGoods(Orders orders, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Orders> page = ordersService.findPageForGoods(new Page<Orders>(request, response), orders);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑交易订单表单页面
	 */
	@RequiresPermissions(value={"orders:orders:view","orders:orders:add","orders:orders:edit"},logical=Logical.OR)
	@RequestMapping(value = "form/{mode}")
	public String form(@PathVariable String mode, Orders orders, Model model) {
		model.addAttribute("orders", orders);
		model.addAttribute("mode", mode);
		return "modules/orders/ordersForm";
	}

	/**
	 * 保存交易订单
	 */
	@ResponseBody
	@RequiresPermissions(value={"orders:orders:add","orders:orders:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Orders orders, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(orders);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		ordersService.save(orders);//保存
		j.setSuccess(true);
		j.setMsg("保存交易订单成功");
		return j;
	}
	
	/**
	 * 删除交易订单
	 */
	@ResponseBody
	@RequiresPermissions("orders:orders:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Orders orders) {
		AjaxJson j = new AjaxJson();
		ordersService.delete(orders);
		j.setMsg("删除交易订单成功");
		return j;
	}
	
	/**
	 * 批量删除交易订单
	 */
	@ResponseBody
	@RequiresPermissions("orders:orders:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			ordersService.delete(ordersService.get(id));
		}
		j.setMsg("删除交易订单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("orders:orders:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(Orders orders, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "交易订单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Orders> page = ordersService.findPage(new Page<Orders>(request, response, -1), orders);
    		new ExportExcel("交易订单", Orders.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出交易订单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("orders:orders:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Orders> list = ei.getDataList(Orders.class);
			for (Orders orders : list){
				try{
					ordersService.save(orders);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条交易订单记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条交易订单记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入交易订单失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入交易订单数据模板
	 */
	@ResponseBody
	@RequiresPermissions("orders:orders:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "交易订单数据导入模板.xlsx";
    		List<Orders> list = Lists.newArrayList(); 
    		new ExportExcel("交易订单数据", Orders.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }


	/**
	 * 确认收款
	 */
	@ResponseBody
	@RequestMapping(value = "confirmCollection")
	public AjaxJson confirmCollection(String ids) {
		AjaxJson j = new AjaxJson();
		ordersService.businessManage(ids);

		j.setMsg("确认收款成功");
		return j;
	}


	/**
	 * 释放订单
	 */
	@ResponseBody
	@RequestMapping(value = "releaseOrder")
	public AjaxJson releaseOrder(String ids) {
		AjaxJson j = new AjaxJson();
		ordersService.releaseBusinessOrder(ids);

		j.setMsg("释放订单成功");
		return j;
	}

}